'use strict';

const jwt = require('jsonwebtoken');

module.exports = {
    jwt_ver: 1,
    // eslint-disable-next-line jsdoc/require-param
    /**
     * 生成Token_login
     * @params {Number} user_id (无默认值)
     * @params {Number} user_lv (默认1)
     * @params {String} is_vip (默认false)
     * @params {String} is_admin (默认false)
     * @params {Number} expiresIn (默认一年有效期, 应用为登录)
     */
    async encodeToken_login(options = {}) {
        const {
            user_id,
            user_lv = 1,
            is_vip = false,
            is_admin = false
        } = options;
        if (isNaN(user_id)) {
            throw new Error(`Please check the 'encodeToken_login()' comments !`);
        }
        const tokenBody = {
            user_id,
            user_lv,
            is_vip,
            is_admin,
            jwr_ver: this.jwt_ver
        };
        return await this.encodeToken(tokenBody);
    },
    // jwt编码
    async encodeToken(options = {}) {
        const {
            expiresIn = 60 * 60 * 24 * 365
        } = options;
        return jwt.sign(options, 'KujoMiva', { expiresIn });
    },
    // jwt解码
    async decodeToken(token) {
        return jwt.verify(token, 'KujoMiva');
    }
};
